//
//  UserLoginViewController.swift
//  SitPosition
//
//  Created by apple on 2018/12/31.
//  Copyright © 2018 apple. All rights reserved.
//

import Foundation
import UIKit
import Cartography
import Toast_Swift


class UserLoginViewController : UserLoginRegistrationBaseViewController {
    
    // MARK: - Subviews
    
    // 用户名
    lazy var usernameTextfield: TextFieldWithLRView = {
        let tf = _buildTextField(placeholder: Strings.logonUsernamePlaceholder,
                                 leftView: UIImageView(image: UIImage(named: "logon_name")))
        tf.delegate = self
        tf.keyboardType = .namePhonePad
        tf.returnKeyType = .next
        tf.clearButtonMode = .whileEditing
        return tf
    }()
    
    // 密码框
    lazy var passwordTextfield: TextFieldWithLRView = {
        let tf = _buildTextField(placeholder: Strings.logonNewPasswordPlaceholder,
                                 leftView: UIImageView(image: UIImage(named: "logon_key")))
        tf.delegate = self
        tf.keyboardType = .default
        tf.returnKeyType = .done
        tf.isSecureTextEntry = true
        return tf
    }()
    
    // 登录按钮
    lazy var logonButton: UserLogonStateButton = {
        let button = UserLogonStateButton(title: Strings.logonNow)
        button.addTarget(self, action: #selector(_logonNow), for: UIControl.Event.touchUpInside)
        return button
    }()
    
    // 底部注册栏
    lazy var registerBtn: UIButton = _bottomBarButton(Strings.logonRegister,
                                                      action: #selector(_registerUser))
    lazy var forgotPasswordBtn: UIButton = _bottomBarButton(Strings.logonForgotPassword,
                                                            action: #selector(_forgotPassword))
    
    let seperator1 = UIView.colored(Theme.Color.primaryBlueSeperatorColor)
    let seperator2 = UIView.colored(Theme.Color.primaryBlueSeperatorColor)
    let seperator3 = UIView.colored(Theme.Color.primaryLightTextColor)
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        gk_navLeftBarButtonItem = UIBarButtonItem(imageName: "ic_nav_back", target: self, action: #selector(_backButtonTapped))
        
        // 设置Views
        view.addSubviews([
            titleLabel,
            usernameTextfield,
            seperator1,
            passwordTextfield,
            seperator2,
            logonButton,
            bodyIV,
            registerBtn,
            seperator3,
            forgotPasswordBtn,
        ])
        _setupContraints()
        titleLabel.text = Strings.logonTitle
    }
    
}

// MAKR: - Private Methods

extension UserLoginViewController {
    
    // 底部工具栏的“注册”、“忘记密码”按钮
    func _bottomBarButton(_ title: String, action: Selector) -> UIButton {
        let btn = UIButton(type: UIButton.ButtonType.custom)
        btn.setTitle(Strings.logonRegister, for: UIControl.State.normal)
        btn.setTitleColor(Theme.Color.primaryLightTextColor, for: UIControl.State.normal)
        btn.titleLabel?.font = Theme.Font.regularFont(ofSize: 14)
        btn.setTitle(title, for: UIControl.State.normal)
        btn.addTarget(self, action: action, for: UIControl.Event.touchUpInside)
        return btn
    }
    
    // 设置视图约束
    func _setupContraints() {
        // titleLabel
        constrain(titleLabel, gk_navigationBar, view) { v, sibling, parent in
            v.top == sibling.bottom + 34
            v.left == parent.left + 40
            v.right == parent.right - 40
            v.height == 25
        }
        
        // usernameTextfield
        let kTextfieldHeight: CGFloat = 36
        constrain(usernameTextfield, titleLabel) { v, sibling in
            v.top == sibling.bottom + 48
            v.left == sibling.left
            v.height == kTextfieldHeight
            v.right == sibling.right
        }
        
        // seperator1
        constrain(seperator1, usernameTextfield) { v, sibling in
            v.top == sibling.bottom+4
            v.left == sibling.left
            v.right == sibling.right
            v.height == 1
        }

        // passwordTextfield
        constrain(passwordTextfield, seperator1) { v, sibling in
            v.top == sibling.bottom + 37
            v.left == sibling.left
            v.height == kTextfieldHeight
            v.right == sibling.right
        }
        
        // seperator2
        constrain(seperator2, passwordTextfield) { v, sibling in
            v.top == sibling.bottom+4
            v.left == sibling.left
            v.right == sibling.right
            v.height == 1
        }
        
        // logonButton
        constrain(logonButton, seperator2) { v, sibling in
            v.width == 200
            v.height == 55
            v.top == sibling.bottom + 30
            v.left == sibling.left
        }
        
        // bodyIV
        constrain(bodyIV, logonButton, view) { v, sibling, parent in
            v.top <= sibling.bottom + 45 ~ .defaultLow
            v.left == parent.left
            v.right == parent.right
            v.bottom == parent.bottom
        }
        
        // registerBtn
        constrain(seperator3, view) { v, parent in
            v.width == 1
            v.height == 15
            v.centerX == parent.centerX
            v.bottom == parent.bottom - 60
        }
        constrain(registerBtn, seperator3, view) { v, sibling, parent in
            v.width == 56
            v.height == 15
            v.right == sibling.left - 20
            v.centerY == sibling.centerY
        }
        constrain(forgotPasswordBtn, seperator3, view) { v, sibling, parent in
            v.width == 56
            v.height == 15
            v.left == sibling.right + 20
            v.centerY == sibling.centerY
        }
    }
    
    // 返回按钮点击事件
    @objc func _backButtonTapped() {
        backCallback()
    }
    
    // 立即登录
    @objc func _logonNow() {
        let cs: CharacterSet = CharacterSet.whitespacesAndNewlines
        guard let mobile = usernameTextfield.text?.trimmingCharacters(in: cs), !mobile.isEmpty,
            let password = passwordTextfield.text, !password.isEmpty else {
                view.makeToast(Strings.logonUsernamePasswordEmpty,
                               duration: Theme.Toast.normalDuration,
                               position: .center)
            return
        }
        view.endEditing(true)
        view.makeToastActivity(.center)
        UserManager.manager.login(mobile, password: password) { [weak self] (error) in
            self?.view.hideToastActivity()
            self?._loginPostHandle(error)
        }
    }
    
    // 登录成功、失败后处理流程
    func _loginPostHandle(_ error: Error?) {
        if UserManager.manager.isLogin() {
            topmostView()?.makeToast(Strings.logonSuccess,
                           duration: Theme.Toast.normalDuration,
                           position: .center)
            backCallback()
        } else {
            view.makeToast(error?.networkErrorMessage ?? Strings.logonFailed,
                           duration: Theme.Toast.normalDuration,
                           position: .center)
        }
    }
    
    // 账号注册
    @objc func _registerUser() {
        let vc = UserRegistionViewController()
        vc.backCallback = { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        vc.successCallback = { [weak self] in
            self?.backCallback()
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
    // 忘记密码
    @objc func _forgotPassword() {
        let vc = UserFindPasswordViewController()
        vc.backCallback = { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - UITextFieldDelegate

extension UserLoginViewController : UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text: String = textField.text ?? ""
        guard let range_: Range = text.toRange(range) else { return true }
        let newString = text.replacingCharacters(in: range_, with: string)
        guard newString.count < kMaxPhonePasswordLength else { return false }
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == usernameTextfield {
            passwordTextfield.becomeFirstResponder()
        } else if textField == passwordTextfield {
            textField.resignFirstResponder()
        }
        return true
    }
}

